<script setup>
import { reactive, ref } from 'vue'

import { imageUrlToFileObject } from '@/utils/toFile'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

import { Plus } from '@element-plus/icons-vue'

import { getPetList } from '@/api/pet'
import { getPetDetectives } from '@/api/petDetectives'
import { postNoteService } from '@/api/note'
import { attentionService } from '@/api/attention'

// import { payOrderService } from '@/api/order'

// 默认数据
const defaultModel = {
    petId: '',
    title: '',
    content: '',
    visibility: false,
    reward: 0,
    files: [],
    userIds: []
}

const imageUrl = reactive(new Map())
const onSelectFile = (uploadFile) => {
    console.log('uploadFile：', uploadFile.raw)
    // console.log(uploadFile.raw.uid);
    const img = URL.createObjectURL(uploadFile.raw)
    imageUrl.set(uploadFile.raw, img)
    // formModel.value.file.push(uploadFile.raw)
}

const onRemoveFile = (uploadFile) => {
    console.log('删除的文件', uploadFile.raw);
    imageUrl.delete(uploadFile.raw)
    // formModel.value.file.splice(index, 1)
}

const formModel = ref({ ...defaultModel })
const formRef = ref()
const editorRef = ref()

const rules = {
    petId: [
        { required: true, message: '请选择宠物', trigger: 'change' }
    ],
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { max: 36, message: '长度最大为36个字符', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入内容', trigger: 'blur' }
    ],
    visibility: [
        { required: true, message: '请选择可见性', trigger: 'change' }
    ],
    reward: [
        { required: true, message: '请输入悬赏', trigger: 'blur' },
    ],
    files: [
        { required: false, message: '请上传文件', trigger: 'change' }
    ],
    userIds: [
        { required: false, message: '请选择用户', trigger: 'change' }
    ]
}
const title = ref('')
const isShow = ref(false)
const disable = ref(false)
const showPerson = ref(false)
const owner = ref(false)
const follow = ref(false)

const open = async (row) => {
    await getPetListData()
    await getPetDetectivesData()
    console.log('传递过来的数据：', row);
    if (Reflect.ownKeys(row.data).length === 0) {
        showPerson.value = true
        formModel.value == { ...defaultModel }
        imageUrl.clear()
    } else {
        // 回显
        follow.value = row.data.follow
        owner.value = row.data.owner
        disable.value = true
        formModel.value = { ...row.data }
        formModel.value.petId = row.data.noteId
        editorOption.value = {
            modules: {
                toolbar: []
            }
        }
        for (let i of row.data.resourcePath) {
            imageUrl.set(i, i)
        }
        // userid 显示
    }
    title.value = row.title
    isShow.value = true
}

// 关闭抽屉
const handleClose = () => {
    formModel.value = { ...defaultModel }
    imageUrl.clear()
    editorRef.value.setText('')
    isShow.value = false
}

// 发布
// const p = ref()
const disPublish = ref(false)
const onPublish = async () => {
    await formRef.value.validate()
    console.log('提交前表单的内容：', formModel.value);
    try {
        disPublish.value = true
        const form = new FormData()
        for (let i in formModel.value) {
            if (i === 'files') {

                for (let [item, index] of imageUrl) {
                    // console.log('item：', item);
                    // console.log('index：', index);
                    form.append(i, await imageUrlToFileObject(index, item.name))
                }
                // form.set(i, cur)
            } else {
                form.append(i, formModel.value[i])

            }
        }

        console.log('提交后的表单内容：', form);
        const { data } = await postNoteService(form)
        ElMessage({
            message: '即将前往支付...',
            type: 'success'
        })
        sessionStorage.setItem('orderId', data)
        window.open('./pay', '_blank')
        // const res = await payOrderService(data)
        // p.value.innerHTML = res.data;
        // p.value.childNodes[0].submit();
    } finally {
        handleClose();
        disPublish.value = false
    }
}


//关注
const handleAttention = async () => {
    await attentionService(formModel.value.petId)
    ElMessage({
        message: '关注成功',
        type: 'success'
    })
    handleClose()
}

defineExpose({
    open
})
// 获取宠物列表
const petList = ref([])
const getPetListData = async () => {
    const { data } = await getPetList(1, 3)
    // console.log(data);
    petList.value = data.list.filter(item => item.bind === true)
}
// 获取宠物侦探列表
const detectiveList = ref([])
const getPetDetectivesData = async () => {
    const { data } = await getPetDetectives()
    detectiveList.value = data
}

// 编辑器配置
const editorOption = ref({
    modules: {
        toolbar: [['bold', 'italic', 'underline', 'strike'], ['link'], ['html']]
    }
})

</script>
<template>
    <!-- <div class="p" ref="p"></div> -->
    <div>
        <el-drawer @close="handleClose" v-model="isShow" :title="title" direction="rtl" size="50%">
            <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px">
                <el-form-item label="宠物" prop="petId">
                    <el-select :disabled="disable" v-model="formModel.petId" placeholder="请选择宠物">
                        <el-option v-for="item in petList" :key="item.petId" :label="item.petName"
                            :value="item.petId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input :disabled="disable" v-model="formModel.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="文章内容" prop="content">
                    <div class="editor">
                        <QuillEditor
                            :style="{ 'pointer-events': disable ? 'none' : 'auto', 'opacity': disable ? '0.5' : '1' }"
                            content-type="html" theme="snow" v-model:content="formModel.content" ref="editorRef"
                            :options="editorOption">
                        </QuillEditor>
                    </div>
                </el-form-item>
                <el-form-item label="可见性" prop="visibility">
                    <el-radio-group :disabled="disable" v-model="formModel.visibility">
                        <el-radio label="公开" :value="true">公开</el-radio>
                        <el-radio label="私密" :value="false">私密</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="悬赏" prop="reward">
                    <el-input-number :disabled="disable" v-model="formModel.reward" :min="100" :max="10000"
                        placeholder="请输入悬赏"></el-input-number>
                </el-form-item>
                <el-form-item label="文件" prop="files">
                    <el-upload :disabled="disable" class="avatar-uploader" :on-change="onSelectFile"
                        :on-remove="onRemoveFile" accept="image/*" limit="3" :file-list="formModel.files"
                        :auto-upload="false">
                        <img v-if="imageUrl.size" v-for="[key, value] of imageUrl" :src="value" :key="key"
                            class="pic" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item v-if="!formModel.visibility && showPerson" label="用户" prop="userIds">
                    <el-select :disabled="disable" mutiple v-model="formModel.userIds" placeholder="请选择用户">
                        <el-option v-for="(item, index) in detectiveList" :key="index" :label="item"
                            :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button v-if="!disable" type="primary" @click="onPublish">发布</el-button>
                    <el-button v-if="!owner && disable && !follow" type="danger" @click="handleAttention">关注</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>
<style scoped lang='scss'>
.avatar-uploader .pic {
    width: 178px;
    height: 178px;
    border-radius: 5px;
    display: block;
    margin: 1rem;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }

}
</style>